package com.jt.provider.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.jt.provider.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/provider")
public class ProviderSentinelController {
    @GetMapping("/sentinel01")
    public String sentinel01(){
        return "sentinel 01 test";
    }
    @GetMapping("/sentinel02")
    public String sentinel02(){
        return "sentinel 02 test";
    }
    @Autowired
    private ResourceService resourceService;
    @GetMapping("/sentinel03")
    public String sentinel03(){
//        resourceService.doGetResource();
        return resourceService.doGetResource();
    }
    @GetMapping("/sentinel04")
    public String sentinel04(){
        resourceService.doGetResource();
        return "sentinel 04 test";
    }
    //AtomicLong 是java.util.concurrent.atomic包中的线程安全对象
    //基于此对象实现自增,自减操作时,是线程安全的
    private AtomicLong atomicLong=new AtomicLong(1);
    @GetMapping("/sentinel05")
    public synchronized String sentinel05()throws Exception {
       Long count=atomicLong.getAndIncrement();//先取值,再加1
        if(count%2==0){
            Thread.sleep(200);//模拟耗时消耗
            throw new RuntimeException("exception...");
        }


        return "sentinel 05 test";
    }
    @GetMapping("/sentinel06")
//    @SentinelResource("selectById")
    public synchronized String sentinel06(@RequestParam("id") Integer id) {
        return resourceService.doGetResource1(id);
       //return "sentinel 06 test id="+id;
    }
}
